package com.atguigu.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName NyMetaObjectHandler.java
 * @Description TODO
 * @createTime 2022年02月01日 14:27:00
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

        log.info("insert 自动填充...........");

        //实现填充的业务逻辑
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
        this.strictUpdateFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
        //判断当前属性中是否有值
        Object age = this.getFieldValByName("age", metaObject);
        if (age == null){
            //当前值为null 开始执行自动填充功能 一般情况下 用户自定义属性值 遇到create_time 或者update_time在使用自动填充
            // 表比较少的时候 不建议全部字段使用自动填充
            this.strictInsertFill(metaObject,"age", Integer.class,3);
        }
        //判断当前属性值是否存在
        boolean author = metaObject.hasSetter("author");
        if (author) {
            this.strictInsertFill(metaObject,"author",String.class,"石头");
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        log.info("update 自动填充...........");

        this.strictUpdateFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());
    }
}
